package net.zjitc.security;

import cn.hutool.json.JSONUtil;
import net.zjitc.common.ResponseResult;
import net.zjitc.exception.CaptchaException;
import org.apache.ibatis.cache.CacheException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 毛钰深
 * @create 2022/1/23
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //设置响应头
        httpServletResponse.setContentType("application/json;charset-UTF-8");
        //获取response的输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        ResponseResult res=new ResponseResult<>();

        //验证码错误异常继承的异常也是同一个的,e只能是AuthenticationException类型或他的子类
        //捕获的异常的范围要从小到大捕获
        try{
            throw e;
        }catch (CaptchaException ex1) {
            res.setError("验证码错误");
        }catch (AuthenticationException ex2){
            res.setError("用户名或者密码错误");
        }

        //使用工具类将res的数据写到输出流中并返回
        outputStream.write(JSONUtil.toJsonStr(res).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
